package com.example.demo.config;


import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author wukq
 * @create 2024/8/30 14:33
 */

@Configuration
@MapperScan(basePackages = "com.example.demo.master.mapper", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSource {

	/**
	 * 返回master数据库的数据源
	 *
	 * @return
	 */
	@Primary
	@Bean(name = "masterSource")
	@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}

	/**
	 * 返回master数据库的会话工厂
	 *
	 * @param ds
	 * @return
	 * @throws Exception
	 */
	@Primary
	@Bean(name = "masterSqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("masterSource") DataSource ds) throws Exception {
		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
		MybatisConfiguration configuration = new MybatisConfiguration();
//		configuration.addInterceptor(new PaginationInterceptor());
		bean.setConfiguration(configuration);
		bean.setDataSource(ds);
		return bean.getObject();
	}

	/**
	 * 返回master数据库的会话模板
	 *
	 * @param sessionFactory
	 * @return
	 * @throws Exception
	 */
	@Primary
	@Bean(name = "masterSqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sessionFactory) throws Exception {
		return new SqlSessionTemplate(sessionFactory);
	}

	/**
	 * 返回master数据库的事务
	 *
	 * @param ds
	 * @return
	 */
	@Primary
	@Bean(name = "masterTransactionManager")
	public DataSourceTransactionManager transactionManager(@Qualifier("masterSource") DataSource ds) {
		return new DataSourceTransactionManager(ds);
	}

}
